package process

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"
	"web/tsuna"

	"web/conf"

	jsoniter "github.com/json-iterator/go"
)

func Find_sublist(startDateTime string, endDateTime string) string {

	var sublist SUBLIST
	Result, _ := tsuna.GetscanWithcol_2(conf.Sublist, startDateTime, endDateTime, conf.Famcel,
		"subid", "eventid")
	for k := 0; k < len(Result); k++ {
		var Evtype string
		for _, v := range Result[k].Cells {
			qua := string(v.Qualifier[:])
			value := string(v.Value[:])
			if "eventid" == qua {
				Evtype = value
			}
		}
		if "SLICE" == Evtype {
			sublist.NSI_LOAD_LEVEL += 1
		}
	}

	b, err := json.Marshal(sublist)
	if err != nil {
		fmt.Println("error:", err)
	}

	var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
	b, err = json_iterator.Marshal(sublist)
	//os.Stdout.Write(b)
	return (string)(b)
}

func Find_level(startDateTime string, endDateTime string) string {
	var NSI_LOAD_LEVEL NSILOADLEVEL
	var subtime SUBTIME
	var Evtype string
	Lever_subid_Result, _ := tsuna.GetscanWithcol_2(conf.Sublist, startDateTime, endDateTime, conf.Famcel,
		"subid", "eventid")

	for k := 0; k < len(Lever_subid_Result); k++ {
		for _, v := range Lever_subid_Result[k].Cells {
			row := string(v.Row[:])
			qua := string(v.Qualifier[:])
			value := string(v.Value[:])
			if "subid" == qua {
				subtime.SubscrptionId = value
				subtime.TimeStamp = row
			}
			if "eventid" == qua {
				Evtype = value
			}
		}
		if "SLICE" == Evtype {
			NSI_LOAD_LEVEL.NSI_LOAD_LEVEL = append(NSI_LOAD_LEVEL.NSI_LOAD_LEVEL, subtime)
		}

	}

	b, err := json.Marshal(NSI_LOAD_LEVEL)
	if err != nil {
		fmt.Println("error:", err)
	}

	var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
	b, err = json_iterator.Marshal(NSI_LOAD_LEVEL)
	//os.Stdout.Write(b)

	return (string)(b)
}

func Find_subinfo(subscrptionId string) string {

	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	var subinfokey []string
	var analpred AnalPred
	var analysislist AnalyPredic
	//var prediction Prediction
	var analydata ANALYDATA
	var timePeriod TIMEPERIOD
	var snssaiid SNSSAIID
	var starttime KVStr
	var kv KVStr
	var kvnum KVInt
	var NsiId string
	var res Res
	subinfokey_Result, _ := tsuna.GetRow(conf.Subinfo, subscrptionId)
	for _, v := range subinfokey_Result.Cells {
		row := string(v.Row[:])
		value := string(v.Value[:])
		//subkey := "subid=" + row + "&" + value
		subkey := row + "_" + value
		subinfokey = append(subinfokey, subkey)
	}
	if 0 == len(subinfokey) {
		return ""
	}

	for m := 0; m < 2; m++ {
		var tablename string
		if 1 == m {
			tablename = conf.Subpreres
			continue
		} else {
			tablename = conf.Subanares
		}
		for k := 0; k < len(subinfokey); k++ {
			snssaiid.Sd = ""
			snssaiid.Sst = 0
			NsiId = ""
			time_Result, _ := tsuna.Getcell(tablename, subinfokey[k], conf.Famcel, "startTime")
			for _, v := range time_Result.Cells {
				row := string(v.Row[:])
				qua := string(v.Qualifier[:])
				value := string(v.Value[:])
				if "startTime" == qua {
					Rsplit := strings.Split(row, "_")
					for _, v := range Rsplit {
						res := strings.Index(v, "sst=")
						if res == 0 {
							sstint, _ := strconv.ParseInt(v[(res+4):], 10, 64)
							snssaiid.Sst = sstint
							continue
						}
						res = strings.Index(v, "sd=")
						if res == 0 {
							snssaiid.Sd = v[(res + 3):]
							continue
						}
						res = strings.Index(v, "nid=")
						if res == 0 {
							NsiId = v[(res + 4):]
							continue
						}

					}

					starttime.Name = "开始时间"
					starttime.Value = value
					timePeriod.Start = starttime

					analysislist.SnssaiId = snssaiid
					analysislist.NsiId = NsiId
				}
			}

			Result, _ := tsuna.GetRow(tablename, subinfokey[k])
			for _, v := range Result.Cells {
				qua := string(v.Qualifier[:])
				value := string(v.Value[:])
				if "startTime" != qua {
					timePeriod.Start = starttime
					kv.Name = "结束时间"

					Strisec := qua[0 : len(qua)-3]
					Unixsec, _ := strconv.ParseInt(Strisec, 10, 64)
					Strimec := qua[len(qua)-3:]
					RFC3339 := time.Unix(Unixsec, 0).Format("2006-01-02T15:04:05")
					RFC3339 = RFC3339 + "." + Strimec + "Z"

					kv.Value = RFC3339
					timePeriod.End = kv

					analydata.TimePeriod = timePeriod

					var jsonBlob = []byte(value)
					json.Unmarshal(jsonBlob, &res)

					kvnum.Name = "用户注册数"
					//kvnum.Value, _ = strconv.ParseInt(res.NumOfUeRegist, 10, 64)
					kvnum.Value = res.NumOfUeRegist
					analydata.NumOfUeRegist = kvnum

					kvnum.Name = "PDU会话数"
					//kvnum.Value, _ = strconv.ParseInt(res.NumOfPDUSession, 10, 64)
					kvnum.Value = res.NumOfPDUSession
					analydata.NumOfPDUSession = kvnum

					analysislist.AnalysData = append(analysislist.AnalysData, analydata)
				}
			}
			if 0 == m {
				analpred.AnalysisList = append(analpred.AnalysisList, analysislist)
				analysislist.AnalysData = analysislist.AnalysData[0:0]
			} else {
				analpred.Prediction = append(analpred.Prediction, analysislist)
				analysislist.AnalysData = analysislist.AnalysData[0:0]
			}
		}
	}
	var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
	b, _ := json_iterator.Marshal(analpred)
	//os.Stdout.Write(b)

	return (string)(b)
}

type SUBLIST struct {
	SLICE_LOAD_LEVEL     int64 `json:"SLICE_LOAD_LEVEL"`
	NETWORK_PERFORMANCE  int64 `json:"NETWORK_PERFORMANCE"`
	NF_LOAD              int64 `json:"NF_LOAD"`
	SERVICE_EXPERIENCE   int64 `json:"SERVICE_EXPERIENCE"`
	UE_MOBILITY          int64 `json:"UE_MOBILITY"`
	UE_COMMUNICATION     int64 `json:"UE_COMMUNICATION"`
	QOS_SUSTAINABILITY   int64 `json:"QOS_SUSTAINABILITY"`
	ABNORMAL_BEHAVIOUR   int64 `json:"ABNORMAL_BEHAVIOUR"`
	USER_DATA_CONGESTION int64 `json:"USER_DATA_CONGESTION"`
	NSI_LOAD_LEVEL       int64 `json:"NSI_LOAD_LEVEL"`
}

type NSILOADLEVEL struct {
	NSI_LOAD_LEVEL []SUBTIME `json:"NSI_LOAD_LEVEL"`
}

type SUBTIME struct {
	SubscrptionId string `json:"subscrptionId"`
	TimeStamp     string `json:"timeStamp"`
}

type AnalPred struct {
	AnalysisList []AnalyPredic `json:"AnalysisList"`
	Prediction   []AnalyPredic `json:"Prediction"`
}

type AnalyPredic struct {
	SnssaiId   SNSSAIID    `json:"SnssaiId"`
	NsiId      string      `json:"NsiId"`
	AnalysData []ANALYDATA `json:"AnalysData"`
}

type ANALYDATA struct {
	TimePeriod      TIMEPERIOD `json:"timePeriod"`
	NumOfUeRegist   KVInt      `json:"NumOfUeRegist"`
	NumOfPDUSession KVInt      `json:"NumOfPDUSession"`
}

type TIMEPERIOD struct {
	Start KVStr `json:"start"`
	End   KVStr `json:"end"`
}

type SNSSAIID struct {
	Sst int64  `json:"sst"`
	Sd  string `json:"sd"`
}

type KVStr struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type KVInt struct {
	Name  string `json:"name"`
	Value int64  `json:"value"`
}

type Res struct {
	NumOfUeCount    int64 `json:"ueCount"`
	NumOfPDUCount   int64 `json:"pduCount"`
	NumOfUeRegist   int64 `json:"ueAve"`
	NumOfPDUSession int64 `json:"pduAve"`
}

/*
	indexrow := "1"
	for {
		len, _ := tsuna.Getscount("emp", indexrow, "9")
		fmt.Println(len)

		if "" != indexrow {
			tsuna.PrintScan(tsuna.GetscanWithcol("emp", indexrow, "9", "cf1", "name", 3))
		} else {
			break
		}
		_, indexrow, _ = tsuna.GetscanWithcol("emp", indexrow, "9", "cf1", "name", 3)
	}
}
*/
